<?php
namespace app\admin\controller;

use app\admin\logic\UsersLogic;
use app\admin\model\Users;
use mailer\tp6\Mailer;
use think\captcha\facade\Captcha;
use think\facade\View;
use app\BaseController;
use think\facade\Request;
use think\facade\Session;
use think\facade\Cookie;
use think\exception\ValidateException;
use think\facade\Cache;
use app\admin\controller\SendMessage;

class Login extends BaseController
{
    // 初始化
    protected function initialize()
    {}
    //登录
    public function login()
    {
        echo 1;
        return View::fetch();
    }

    public function loginIn()
    {
        if (Request::isPost()){
            //接值
            $post = Request::post();
            //登录五次判断
            if (!empty(cache($post['name'])) && cache($post['name'])>=5){
                $time = date('Y-m-d H:i:s',time()+86400);
                if (empty(cache($post['name'].'times'))){
                    cache($post['name'].'times',$time,86400);
                }
                $this->error('请在'. cache($post['name'].'times').'后登录');
            }
            //判断是否有验证码
            if (!empty($post['code'])){
                //有验证码
                list($true,$txt) = UsersLogic::usercLogin($post);
            }else{
                //没有验证码
                list($true,$txt) = UsersLogic::userLogin($post);
            }

            if ($true){
                //逻辑层处理条件
                $where = UsersLogic::userWhere($post);
                //模型层做对比
                $res = Users::loginList($where);
            }else{
                $this->error($txt,url('login/login'));
            }
            if ($res){
                //登录成功后成功后将登录者ID存入Session
                Session::set('user',$res['id']);
                //清除判断验证码的Cache缓存
                Cache::delete($post['name']);
                //三十天免登录
                //将登录者ID和md5加密用户名密码存入cookie
                $id = $res['id'];
                $uname = md5($res['uname']);
                $upwd = md5($res['upwd']);
                $cookie = $id.'_'.md5($uname.$upwd);
                if (!empty($post['free']) && isset($post['free'])){
                    cookie('user',$cookie,2592000);
                }
                $this->success('登陆成功',url('index/index'));
            }else{
                //如果失败就将登陆者信息存入cookie判断失败几次
                if (empty(cache($post['name']))){
                    cache($post['name'],1,3600);
                }else{
                    cache($post['name'],cache($post['name'])+1,3600);
                }
                echo \cache($post['name']);
                $this->error('用户名或密码错误,'.cache($post['name']).'次',url('login/login'));
            }
        }
    }


    public function ajaxCode()
    {
        //接值
        $data = Request::param('code');
        if (!captcha_check($data,false)){
            //验证失败
            return 0;
        }
        return 1;
    }
    public function ajaxAccount()
    {
        //AJAX判断是否显示验证码
        //接值
        $data = Request::param();
        if (!empty(cache($data['account']))){
            $res = cache($data['account']);
        }else{
            $res = false;
        }

        return json($res);
    }
    public function loginFree()
    {
        if (Cookie::has('user') && !empty(Cookie::get('user'))){
            //三十天免登录直接登录界面
            //将免登录用户从cookie中取出
            $cookie = cookie('user');
            //将取出的cookie转成数组
            $cookie = explode('_',$cookie);
            //从数据库区该用户的所有信息
            $line = Users::where('id','=',$cookie[0])->find();
            View::assign('line',$line);
            //接值
            $get = Request::get();
            //加密
            $uname = md5($line['uname']);
            $upwd = md5($line['upwd']);
            $find = md5($uname.$upwd);
            if (isset($get['login']) && !empty($get['login'])){
                //判断cookie中的数据能否与数据库匹配
                if ($cookie[1] == $find){
                    Session::set('user',$line['id']);
                    $this->success('登录成功',url('index/index'));
                }else{
                    $this->error('账户过期,请重新登录',url('login/login'));
                }
            }
            return View::fetch();
        }else{
            return View::fetch('login');
        }

    }
    public function ajaxEmail()
    {
        //AJAX发送邮件验证码
        //接值
        $post = Request::post();
        $email = $post['email'];
        $name = $post['name'];
        //取出所有用户名
        $list_name = Users::column('uname');
        //取出所有邮箱
        $list = Users::column('email');
        //判断是否发送验证码等判断
        if (!empty($email) && isset($email) && in_array($email,$list) && in_array($name,$list_name)){
            $code = mt_rand(1111,9999);
            SendMessage::sendMsg($email,'验证码',$code);
            Cache::set('code',$code,30);
            return json(['code'=>1,'msg'=>'验证码发送成功']);
        }
        if (!in_array($name,$list_name)){
            return json(['code'=>2,'msg'=>'没有该用户']);
        }
        if (!in_array($email,$list)){
            return json(['code'=>3,'msg'=>'邮箱不正确']);
        }
        if (empty($email)){
            return json(['code'=>4,'msg'=>'邮箱不能为空']);
        }


    }
    public function loginEdit()
    {
        if (Request::isPost()){
            //接值
            $post = Request::post();
            //判断是否存在Cache
            if (Cache::has('code') && !empty(Cache::has('code'))){
                //判断前台传过来的验证码是否与Cache内相等
                if ($post['code']==Cache::get('code')){
                    //用前台传到后台的数据寻找与数据库用户名和邮件相等的数据
                    $where = Users::where('uname','=',$post['name'])->where('email','=',$post['email'])->find();
                    $data = [
                        'id'    =>$where['id'],
                        'upwd'  =>md5($post['password'])
                    ];
                    $edit = Users::loginEdit($data);
                    if ($edit){
                        Cache::delete('code');
                        $this->success('修改成功',url('login/login'));
                    }else{
                        $this->error('修改失败');
                    }
                }
                if ($post['code']!==Cache::get('code')){
                    $this->error('验证码错误',url('login/loginEdit'));
                }
            }
            //验证码超过cache时间
            if (!Cache::has('code') && empty(Cache::has('code'))){
                $this->error('验证码过期',url('login/loginEdit'));
            }
        }
        return View::fetch();
    }

    public function loginOut()
    {
        //退出时判断是否存在cookie
        if (\cookie('user') && !empty(\cookie('user'))){
            //取出cookie
            $cookie = cookie('user');
            //将cookie转为数组
            $cookie = explode('_',$cookie);
            $line = Users::where('id','=',$cookie[0])->find();
            $find = md5(md5($line['uname']).md5($line['upwd']));
            if ($cookie[1] == $find){
                $this->success('退出成功',url('login/loginFree'));
            }else{
                Cookie::delete('user');
                $this->error('账户过期,请重新登录',url('login/login'));
            }
        }else{
            Session::delete('user');
            $this->success('退出成功',url('login/login'));
        }
    }
}